package com.example.springmvcdemo.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.*;
import javax.websocket.Session;
import java.util.Arrays;

@RestController
@RequestMapping("/request")
public class RequestController {

    // 获取 Cookie
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            Arrays.stream(cookies).forEach(x->{
                System.out.println(x.getName() + ":" + x.getValue());
            });
            return "获取 cookie 成功";
        }
        return "cookie 为空";

//        for (Cookie c : cookies) {
//            System.out.println(c.getName() + ":" + c.getValue());
//        }
    }

    // 只能获取一个
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("frost") String frost) {
        return "frost: " + frost;
    }

    // 获取 Session
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("userName", "zhangsan");
        return "session 设置成功";
    }

    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("userName");
        return "登录用户: " + userName;
    }

    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
//        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("userName");
        return "登录用户: " + userName;
    }

    @RequestMapping("/getSession3")
    public String getSession(@SessionAttribute(value = "userName", required = false) String userName) {
        return "登录用户: " + userName;
    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "UserAgent: " + userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent) {
        //String userAgent = request.getHeader("User-Agent");
        return "UserAgent: " + userAgent;
    }
}
